package com.boyinet.activation.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boyinet.activation.entity.User;
import com.boyinet.activation.mapper.UserMapper;
import com.boyinet.activation.service.UserService;
import com.boyinet.activation.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lengchunyun
 * @since 2021-01-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User getUserByName(String username) {
        return this.baseMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, username));
    }

    @Override
    public IPage<User> listByPage(UserVO condition) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).like(StrUtil.isNotBlank(condition.getNo()), User::getId, condition.getNo());
        return this.baseMapper.selectPage(new Page<>(condition.getPage(), condition.getLimit()), wrapper);
    }

    @Override
    public Boolean unlock(User user) {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        User userByName = getUserByName(name);
        return passwordEncoder.matches(user.getPassword(), userByName.getPassword());
    }
}
